<?php


namespace Staff\Model;

use Zend\Db\Sql\Sql;
use Zend\Db\TableGateway\TableGateway;
use Zend\Form\Element\Select;

class StaffTable
{
    protected $tableGateway;
    protected $adapter;

    public function __construct(TableGateway $tableGateway)
    {
        $this->tableGateway = $tableGateway;
        $this->adapter = $tableGateway->getAdapter();
    }

    public function fetchAll()
    {
        $resultSet = $this->tableGateway->select();
        return $resultSet;
    }

    public function findStaff($column = null, $parame = null)
    {
        $select = $this->tableGateway->getSql()->select();
        if ($column) $select->where->like($column, '%' . $parame . '%');
        $select = $select->join('pc_bank', 'pc_staff.bank_id = pc_bank.bank_id', array('bank_name'));
        $resultSet = $this->tableGateway->selectWith($select);
        return $resultSet;
    }

    public function getStaff($staff_id)
    {
        $rowset = $this->tableGateway->select(array('staff_id' => $staff_id));
        $row = $rowset->current();
        if (!$row) throw new \Exception("Could not find doc by $staff_id");
        return $row;
    }

    public function setStaff(Staff $staff)
    {
        $data = array(
            'staff_name' => $staff->staff_name,
            'staff_tel' => $staff->staff_tel
        );
        $staff_id = $staff->staff_id;
        if (is_null($staff_id)) $this->tableGateway->insert($data);
        elseif ($this->getStaff($staff_id)) $this->tableGateway->update($data, array('staff_id' => $staff_id));
        else throw new \Exception('Staff id does not exist');
    }

    public function deleteStaff($staff_id)
    {
        $this->tableGateway->delete(array('staff_id' => $staff_id));
    }

    public function getStaffByStaffId($staff_id)
    {
        $select = $this->tableGateway->getSql()->select();
        $select = $select->join('pc_bank', 'pc_staff.bank_id = pc_bank.bank_id', array('bank_name'));
        $select = $select->where(array('staff_id' => $staff_id));
        $resultSet = $this->tableGateway->selectWith($select);
        return $resultSet->current();
    }

    /**
     * 获取某支行的所有职工
     * @param $bank_id
     * @return array
     */
    public function getStaffByBankId($bank_id)
    {
        $resultSet = $this->tableGateway->select(array('bank_id' => $bank_id));
        return $resultSet->toArray();
    }
}